package memberlayer

import (
    "time"
    "errors"
	"encoding/json"
	"dhfshop/models/member"
	"dhfshop/models/consts"
	"dhfshop/service/nsqcli"
	"github.com/astaxie/beego"
)

func sendIntegralMsg(partnerId, memberId int64, integral int) {
	integralNsq := struct {
		PartnerId int64  `json:"partner_id"`
		MemberId  int64  `json:"member_id"`
		Integral  int    `json:"integral"`
		Time      string `json:"time"`
	}{PartnerId:partnerId,MemberId:memberId,Integral:integral,Time:time.Now().UTC().Format(consts.DATETIME_FORMAT)}
	if b, err := json.Marshal(integralNsq); err == nil {
		address := beego.AppConfig.String("NsqUrl")
		topic := "MemberUpgrade"
		if err = nsqcli.StartProducer(address, topic, b); err != nil {
			beego.Debug("StartProducer err:", err.Error())
		}
	}else{
	    beego.Debug("sendIntegralMsg err:", err.Error())
	}
}

// 增加积分：会员赚积分：交易、完善个人信息资料；每日签到。
func AddIntegral(partnerId,curUserId int64,srcAccount *member.Account,value int,remark string) (logId int64, err error) {
	srcIntegral := srcAccount.Integral
	srcAccount.Integral += value
	dstIntegral := srcAccount.Integral
	if err = member.UpdateAccountById(srcAccount, "integral"); err != nil {
		return
	}
	log := &member.IntegralLog{
		PartnerId: partnerId,
		MemberId:  curUserId,
		BusinessKind: TypeIntegralFreeze,
		SrcIntegral:  srcIntegral,
		IncIntegral:  value,
		DstIntegral:  dstIntegral,
		Remark:       remark,
	}	
	logId, err = member.AddIntegralLog(log)
	//
	sendIntegralMsg(partnerId, curUserId, srcAccount.Integral)
	//
	return
}

// 扣减积分：会员花积分：积分兑换商品；积分充话费、充值Q币；兑换优惠券。
func DiscountIntegral(partnerId,curUserId int64,srcAccount *member.Account,value int,remark string) (logId int64, err error) {
	if srcAccount.Integral < value {
		err = errors.New(ErrNoSuchIntegral.Error())
		return
	}
	srcIntegral := srcAccount.Integral
	srcAccount.Integral -= value
	dstIntegral := srcAccount.Integral
	if err = member.UpdateAccountById(srcAccount, "integral"); err != nil {
		return
	}
	log := &member.IntegralLog{
		PartnerId: partnerId,
		MemberId:  curUserId,
		BusinessKind:  TypeIntegralFreeze,
		SrcIntegral: srcIntegral,
		IncIntegral: value,
		DstIntegral: dstIntegral,
		Remark:    remark,
	}	
	logId, err = member.AddIntegralLog(log)
	//
	sendIntegralMsg(partnerId, curUserId, srcAccount.Integral)
	//
	return
}

// 冻结积分
func FreezesIntegral(partnerId,curUserId int64,srcAccount *member.Account,value int,remark string)(logId int64, err error) {
	if srcAccount.Integral < value {
		err = errors.New(ErrNoSuchIntegral.Error())
		return
	}
	SrcIntegral := srcAccount.Integral
	srcAccount.Integral -= value
	DstIntegral := srcAccount.Integral
	srcAccount.FreezeIntegral += value
	if err = member.UpdateAccountById(srcAccount, "integral", "freeze_integral"); err != nil {
		return
	}
	log := &member.IntegralLog{
		PartnerId: partnerId,
		MemberId:  curUserId,
		BusinessKind:  TypeIntegralFreeze,
		SrcIntegral: SrcIntegral,
		IncIntegral: value,
		DstIntegral: DstIntegral,
		Remark:      remark,
	}	
	logId, err = member.AddIntegralLog(log)
	return
}
		
// 解冻积分
func UnfreezesIntegral(partnerId,curUserId int64,srcAccount *member.Account,value int,remark string)(logId int64, err error) {
	if srcAccount.FreezeIntegral < value {
		err = errors.New(ErrNoSuchIntegral.Error())
		return
	}
	SrcIntegral := srcAccount.Integral
	srcAccount.Integral += value
	DstIntegral := srcAccount.Integral
	srcAccount.FreezeIntegral -= value
	if err = member.UpdateAccountById(srcAccount, "integral", "freeze_integral"); err != nil {
		return
	}
	log := &member.IntegralLog{
		PartnerId: partnerId,
		MemberId:  curUserId,
		BusinessKind: TypeIntegralFreeze,
		SrcIntegral: SrcIntegral,
		IncIntegral: value,
		DstIntegral: DstIntegral,
		Remark:      remark,
	}	
	logId, err = member.AddIntegralLog(log)
    return
}

// 更新账户
func UpdateAccountForOrder(partnerId,curUserId int64,account *member.Account,memberExperienceEnabled bool,amount,
                           experienceRateByOrder,integralRateByConsumption float32) (err error) {
	// 增加经验
	if memberExperienceEnabled {
		/*
		rate := experienceRateByOrder
		if exp := int32(amount * float64(rate)); exp > 0 {
			if err = m.AddExp(exp); err != nil {
				return err
			}
		}
		*/
	}
	// 增加积分
	iRate := integralRateByConsumption
	integral := int(amount*iRate)
	// 赠送积分
	if integral > 0 {
		if _, err = AddIntegral(partnerId,curUserId,account,integral,""); err != nil {
			return err
		}
	}
	account.TotalConsume += amount
	account.TotalPay += amount
	err = member.UpdateAccountById(account, "total_consume", "total_pay")
	return
}

func UpdateAccountForRefund(partnerId,curUserId int64,account *member.Account,amount,integralRateByConsumption float32) (err error) {
	iRate := integralRateByConsumption
	integral := int(amount*iRate)
	if integral > 0 {
		if _, err = DiscountIntegral(partnerId,curUserId,account,integral,""); err != nil {
			return err
		}
	}
	account.TotalConsume -= amount
	account.TotalPay -= amount
	err = member.UpdateAccountById(account, "total_consume", "total_pay")
	return
}

